package org.wby.jwt.config.security;

import com.google.gson.Gson;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义授权失败异常处理
 */
//@Component
@Slf4j
public class CustomerAccessDenieyHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {

        Map<String, Object> resultMap = new HashMap<String, Object>(16);
        resultMap.put("success", false);
        resultMap.put("message", "抱歉，您没有权限访问");
        resultMap.put("code", 401);
        resultMap.put("timestamp", System.currentTimeMillis());
        resultMap.put("result", null);

        String resultJson = new Gson().toJson(resultMap);

        response.setContentType( "application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            outputStream.write(resultJson.getBytes(StandardCharsets.UTF_8));
        }catch (Exception e){
            accessDeniedException.printStackTrace();
        }
    }
}
